package com.sn.author.utils;

import com.alibaba.fastjson.JSON;
import com.sn.author.common.context.SessionHelper;
import com.sn.author.common.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author xiaom
 * @Date 2020/9/15 22:08
 * @Version 1.0.0
 * @Description <>
 **/
@Slf4j
public class Analysis {

    private static String _TMP_FILE_DIR = "";

    static {
        if(SystemUtils.isOSLinux()){
            _TMP_FILE_DIR = "/data/tmp/";
            log.info("This system is OSLinux, File path:[{}]",_TMP_FILE_DIR);
        }else{
            _TMP_FILE_DIR = "D:/tmp";
            log.info("This system is Windows, File path:[{}]",_TMP_FILE_DIR);
        }
    }


    private Analysis() {
    }

    public static List<List<Object>> getCourseListByExcel(MultipartFile file) throws Exception {
        List<List<Object>> list = new ArrayList<>();
        if(file == null){
            return list;
        }
        // 创建excel工作簿
        Workbook work = getWorkbook(file.getInputStream(), Objects.requireNonNull(file.getOriginalFilename()));

        Sheet sheet;
        Row row;
        Cell cell;

        for (int i = 0; i < work.getNumberOfSheets(); i++) {

            sheet = work.getSheetAt(i);
            if(sheet == null) {
                continue;
            }

            // 滤过第一行标题
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }

                List<Object> li = new ArrayList<>();

                Object value;
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    value = getCellValue(cell);
                    if(value == null){
                        value = "";
                    }
                    li.add(value);
                }
                if(!li.isEmpty()){
                    list.add(li);
                }
            }
        }
        work.close();
        return list;
    }

    private static Object getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }

        Object obj = null;
        switch (cell.getCellTypeEnum()) {
            case BOOLEAN:
                obj = cell.getBooleanCellValue();
                break;
            case ERROR:
                obj = cell.getErrorCellValue();
                break;
            case FORMULA:
                try {
                    obj = String.valueOf(cell.getStringCellValue());
                } catch (IllegalStateException e) {
                    String valueOf = String.valueOf(cell.getNumericCellValue());
                    BigDecimal bd = new BigDecimal(Double.parseDouble(valueOf));
                    bd = bd.setScale(0, RoundingMode.HALF_UP);
                    obj = Integer.parseInt(bd.toString());
                }
                break;
            case NUMERIC:
                obj = new Double(cell.getNumericCellValue()).longValue();
                break;
            case STRING:
                String value = String.valueOf(cell.getStringCellValue());
                value = value.replace(" ", "");
                value = value.replace("\n", "");
                value = value.replace("\t", "");
                obj = value;
                break;
            default:
                break;
        }
        return obj;
    }

    /**
     * 判断文件格式
     */
    private static Workbook getWorkbook(InputStream in, String fileName) throws Exception {

        Workbook book;
        String filetype = fileName.substring(fileName.lastIndexOf("."));

        if(".xls".equals(filetype)) {
            book = new HSSFWorkbook(in);
        } else if (".xlsx".equals(filetype)) {
            book = new XSSFWorkbook(in);
        } else {
            throw new Exception("请上传excel文件！");
        }

        return book;
    }

    public static List<String> parserFileContent(MultipartFile file) throws IOException {
        if(file == null){
            throw new BadRequestException("上传的文件为空");
        }
        String fileName = file.getOriginalFilename();
        if(fileName == null){
            throw new BadRequestException("异常的上传文件");
        }
        fileName = _TMP_FILE_DIR + DateUtils.formatDate(new Date(),"yyyyMMddHHmm") + "_" + fileName;
        FileUtils.createLevelFile(fileName);
        try {
            file.transferTo(new File(fileName));
            log.info("文件上传成功, filePath:{}",fileName);
        } catch (IOException e) {
            log.error("上传文件失败 e:{}",e.getMessage());
            e.printStackTrace();
        }

        //读取文件
        List<String> accountList = FileUtils.readFileContent(fileName);
        log.info("上传的文件内容:{}", JSON.toJSONString(accountList));
        return accountList;
    }

}
